package com.ctgu.chatapp.Service

import android.util.Log
import com.ctgu.chatapp.Netty.protocol.Message
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.model.Retrofit.IMSServiceImpl
import com.ctgu.chatapp.model.pojo.FriendShip
import com.ctgu.chatapp.model.pojo.RecordNew
import com.ctgu.chatapp.model.pojo.Request
import com.ctgu.chatapp.view.ActivityCollector
import com.ctgu.chatapp.view.FriendChat
import com.ctgu.chatapp.view.IMSApplication
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch

class NotifyService {

    private val TAG = "NotifyService"

    val dataBase = DataBaseManager.getInstance(IMSApplication.context)

    fun solve(msg: Message.IMSMsg) {
        when (msg.bodyType) {
            Message.IMSMsg.BodyType.ChatRequest -> chat(msg)
            Message.IMSMsg.BodyType.FriendRequest -> friendRequest(msg)
            Message.IMSMsg.BodyType.FriendResponse -> friendResponse(msg)
            else -> Unit
        }
    }

    private fun chat(msg: Message.IMSMsg) {
        //聊天消息的处理
        println(msg.head.snowFlowerID)
        when (msg.chatRequest.contentType) {
            Message.ChatRequest.ContextType.word -> {
                val record = RecordNew(
                    msg.head.snowFlowerID,
                    msg.head.toId,
                    msg.head.fromId,
                    0,
                    msg.chatRequest.context,
                    msg.head.timestamp
                )
                CoroutineScope(IO).launch {
                    dataBase.getMsgDao().addRecord(record)
                    RequestService.sendAck(msg.head.snowFlowerID)
                }
                //如果聊天页面再前台运行的话,则可能该消息是正在聊天的用户发去,传给聊天界面的adapter
                if (ActivityCollector.isActivityExist(FriendChat::class.java)) {
                    val message = android.os.Message()
                    message.obj = record
                    message.what = 1
                    FriendChat.handler.sendMessage(message)
                }
            }
            Message.ChatRequest.ContextType.Control -> {
                Log.d(TAG, "chat: 要撤回的消息的ID为 ${msg.chatRequest.snowFlower}")
                CoroutineScope(IO).launch {
                    dataBase.getMsgDao().deleteRecord(msg.chatRequest.snowFlower)
                    RequestService.sendAck(msg.head.snowFlowerID)
                }
                if (ActivityCollector.isActivityExist(FriendChat::class.java)) {
                    val message = android.os.Message()
                    message.what = 2
                    message.obj = msg
                    FriendChat.handler.sendMessage(message)
                }
            }
            else -> {}
        }
    }

    /**
     * todo:用于服务器发来的好友请求的消息
     * */
    private fun friendRequest(msg: Message.IMSMsg) {
        CoroutineScope(IO).launch {
            val information =
                IMSServiceImpl.imsServiceImpl.service.getInformation(msg.head.fromId)
            dataBase.getInformationDao().addInformation(information)
            dataBase.getRequestDao()
                .addFriendRequest(Request(msg.head.toId, msg.head.fromId, 3, msg.head.timestamp))
            Log.d(TAG, "friendRequest: 好友请求的全局唯一ID为:${msg.head.snowFlowerID}")
            RequestService.sendAck(msg.head.snowFlowerID)
        }
    }

    /**
     * todo:用于服务器接受发来的好友请求回复消息
     * */
    private fun friendResponse(msg: Message.IMSMsg) {
        Log.d(TAG, "friendResponse: ${msg.friendResponse.requestType}")
        CoroutineScope(IO).launch {
            dataBase.getRequestDao()
                .updateFriendRequest(
                    msg.friendResponse.id,
                    msg.head.toId,
                    msg.head.fromId
                )
            Log.d(TAG, "friendResponse: 对方同意了请求")
            if (msg.friendResponse.requestType == 1) {
                Log.d(TAG, "friendResponse: ${msg.friendResponse.type}")
                val information =
                    IMSServiceImpl.imsServiceImpl.service.getInformation(msg.head.fromId)
                dataBase.getInformationDao().addInformation(information)
                dataBase.getFriendDao()
                    .addFriendOne(
                        FriendShip(
                            null,
                            msg.head.toId,
                            msg.head.fromId,
                            msg.friendResponse.type
                        )
                    )
            }
            RequestService.sendAck(msg.head.snowFlowerID)
        }
    }
}